package com.wejoy.video.middle.station.data.mybatis.type;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.lang.UsesJava8;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.LocalTimeTypeHandler;

import java.sql.*;
import java.time.LocalTime;

/**
 * 继承了LocalTimeTypeHandler这个类, 重写了对localtime的处理
 * 主要是针对0点返回null的问题
 * @author
 */
@UsesJava8
public class CustomLocalTimeTypeHandler extends LocalTimeTypeHandler {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, LocalTime parameter, JdbcType jdbcType)
          throws SQLException {
    ps.setTime(i, Time.valueOf(parameter));
  }

  @Override
  public LocalTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String stringTime = rs.getString(columnName);
    return getLocalTime(stringTime);
  }

  @Override
  public LocalTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String stringTime = rs.getString(columnIndex);
    return getLocalTime(stringTime);
  }

  @Override
  public LocalTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String stringTime = cs.getString(columnIndex);
    return getLocalTime(stringTime);
  }

  /**
   * 从字符串中解析时间
   * 取出每一位设置为localtime的时,分,秒,毫秒
   * @param stringTime  时间字符串
   * @return
   */
  private LocalTime getLocalTime(String stringTime) {
    if (StringUtils.isEmpty(stringTime)) {
      return null;
    }
    String[] timeSplit = stringTime.split(":");
    if (stringTime.contains(".")) {
      String[] secondSplit = timeSplit[2].split("\\.");
      String nano = secondSplit[1].replaceAll("[0]+$", "");
      return LocalTime.of(Integer.parseInt(timeSplit[0]), Integer.parseInt(timeSplit[1]), Integer.parseInt(secondSplit[0]), Integer.parseInt(nano));
    } else {
      return LocalTime.of(Integer.parseInt(timeSplit[0]), Integer.parseInt(timeSplit[1]), Integer.parseInt(timeSplit[2]));
    }
  }
}
